import time
from pynput import keyboard
import pyautogui
import clipboard
import re

import ffmpeg

import doGetTitle
import doCreatePy
# import doCut

import inputChange


from pynput.keyboard import Key, Controller as KeyboardController

# # 初始化键盘控制器
keyboard_controller = KeyboardController()
# keyboard_controller.press(keyboard.Key.enter)
# keyboard_controller.release(keyboard.Key.enter)

# 设置按键延迟时间
delay_after_command_j = 0.3  # Command+J 后等待时间（秒）
delay_after_command_c = 0.1  # Command+C 后等待时间（秒）

# 设置全局变量atime, btime, 每次点击j和l的时候, 都会刷新
apoint = ''
bpoint = ''
rotation = 0 # 0则旋转0度, 1则90度, 2则270度(实际ffmpeg用2输出时是逆时针旋转90度)
vflip = False # 垂直翻转 

notshift_press_whenlshift_press = False

caps_lock_on = False

# 检测是否按下了 j 键的组合
current_pressed = set()

def is_valid_time_format(time_str):
    """
    判断字符串是否符合 HH:MM:SS.sss 或 MM:SS.sss 时间格式。
    
    参数:
        time_str (str): 要检查的时间字符串。
        
    返回:
        bool: 如果符合格式返回 True，否则返回 False。
    """
    # 正则表达式解释：
    # ^                          -> 开头
    # (\d+:\d{2}:\d{2}(\.\d+)?)  -> 匹配 HH:MM:SS(.mmm)?
    # |                          -> 或者
    # (\d+:\d{2}(\.\d+)?)        -> 匹配 MM:SS(.mmm)?
    # $                          -> 结尾
    pattern = r'^(\d+:\d{2}:\d{2}(\.\d+)?|\d+:\d{2}(\.\d+)?)$'
    
    return re.fullmatch(pattern, time_str) is not None

def turnOnCapslock():
    global caps_lock_on
    if caps_lock_on == False:
        keyboard_controller.press(keyboard.Key.caps_lock)
        keyboard_controller.release(keyboard.Key.caps_lock)
        caps_lock_on = True
def turnOffCapslock():
    global caps_lock_on
    if caps_lock_on == True:
        keyboard_controller.press(keyboard.Key.caps_lock)
        keyboard_controller.release(keyboard.Key.caps_lock)
        caps_lock_on == False   

# 定义键值映射
def key_event(key):
    try:
        return key.vk # j是38
    except:
        return key.value.vk


#  按下时的逻辑
def on_press(key):

    global notshift_press_whenlshift_press
    global caps_lock_on


     
    current_pressed.add(key)
    # print(current_pressed)

    if key == keyboard.Key.caps_lock and len(current_pressed) == 1:
        caps_lock_on = not caps_lock_on
        # print('caps: ', caps_lock_on)

    if keyboard.Key.shift in current_pressed and key != keyboard.Key.shift: 
        notshift_press_whenlshift_press = True
    
        if key == keyboard.Key.space:         
            if(keyboard.Key.shift in current_pressed):
                # turnOffCapslock()
                # 在开大写的情况下, 不用删除一格,否则就要删一格, 因为会输入一个空格键
                keyboard_controller.press(keyboard.Key.backspace)
                keyboard_controller.release(keyboard.Key.backspace)
                inputChange.switchToCn()
                print('cn')
                caps_lock_on = False
    # if doGetTitle.get_frontmost_app() != 'IINA':
    #    pass


# 抬起时的逻辑
def on_release(key):

    global apoint
    global bpoint
    global rotation
    global vflip

    global notshift_press_whenlshift_press
    global caps_lock_on

    # print('shift_press: ', shift_press)
    # print(current_pressed)

    if key != keyboard.Key.shift and keyboard.Key.shift in current_pressed:
        notshift_press_whenlshift_press = True

    if key == keyboard.Key.shift :
        if notshift_press_whenlshift_press == False:
            turnOffCapslock()
            inputChange.switchToEn()
            print('en')
            caps_lock_on = False

        notshift_press_whenlshift_press = False
        


    if doGetTitle.get_frontmost_app() != 'IINA': 
        if key in current_pressed:
            current_pressed.remove(key)
        return


    try:
        # print('cmd is :', current_pressed, key, key_event(key))
        # if key in current_pressed:
        #     current_pressed.remove(key)

        if key_event(key) == 38: # press j
            # print("j pressed, triggering actions...")

            if keyboard.Key.cmd in current_pressed:
                # print("检测到 Command + J 被按下")
                # 在这里执行你想要的操作
                # 例如：模拟其他快捷键操作等
                pass
            else:
                # print("仅检测到 J 被按下")

                # 触发 Command + J
                pyautogui.hotkey('command', 'j')
                time.sleep(delay_after_command_j)

                # 触发 Esc
                pyautogui.press('esc')
                time.sleep(0.3)


                # 第二次触发触发 Command + J
                pyautogui.hotkey('command', 'j')
                time.sleep(delay_after_command_j)


                # 触发 Command + C
                pyautogui.hotkey('command', 'c')
                time.sleep(delay_after_command_c)

                # 从剪贴板获取文本
                clipboard_text = clipboard.paste()
                
                if is_valid_time_format(clipboard_text):
                    apoint = clipboard_text
                    print("\n\nA point: " , clipboard_text)
                else:
                    print('非法时间格式', clipboard_text, '无法被设定为apoint')

                # 触发 Esc
                pyautogui.press('esc')
                # keyboard_controller.press(keyboard.Key.enter)
                # keyboard_controller.release(keyboard.Key.enter)

        elif key_event(key) == 37: # press l:

            if keyboard.Key.cmd in current_pressed:
                # print("检测到 Command + J 被按下")
                # 在这里执行你想要的操作
                # 例如：模拟其他快捷键操作等
                pass
            else:
                # print("仅检测到 J 被按下")

                # 触发 Command + J
                pyautogui.hotkey('command', 'j')
                time.sleep(delay_after_command_j)

                # 触发 Esc
                pyautogui.press('esc')
                time.sleep(0.3)


                # 第二次触发触发 Command + J
                pyautogui.hotkey('command', 'j')
                time.sleep(delay_after_command_j)
                

                # 触发 Command + C
                pyautogui.hotkey('command', 'c')
                time.sleep(delay_after_command_c)

                # 从剪贴板获取文本
                clipboard_text = clipboard.paste()

                if is_valid_time_format(clipboard_text):
                    bpoint = clipboard_text
                    print("B point: " , clipboard_text)
                    print(f'rotation = {rotation}, vflip = {vflip}')
                else:
                    print('非法时间格式', clipboard_text, '无法被设定为bpoint')


                # 触发 Esc
                pyautogui.press('esc')
                # keyboard_controller.press(keyboard.Key.enter)
                # keyboard_controller.release(keyboard.Key.enter)


                # 获得iina正在最前的窗口的标题, 并做正则处理, 以处理后的标题作为.py的文件名
                pyFileName = '_' + doGetTitle.get_iina_window_title() + '.py'

                if not doCreatePy.check_file_exists(pyFileName):
                    doCreatePy.write_head(pyFileName)

                doCreatePy.write_records(apoint, bpoint, rotation, vflip, pyFileName)                
        elif key_event(key) == 43: # 按了','
            rotation = 1 # 旋转90度
            print('set rotation = 1') 
        elif key_event(key) == 47:  # 按了 '.'
            rotation = 2 # 旋转270度(在ffmpeg上是逆时针90度, 效果也是完全一样的)
            print('set rotation = 2')
        elif key_event(key) == 44:  # 按了 '/'
            rotation = 0 # 旋转0度, 就是恢复正常
            print('set rotation = 0')
        elif key_event(key) == 41:  # 按了 ';'
            vflip = not vflip # True就是垂直翻转, False就是恢复正常
            print(f'set vflip = {vflip}')
        else:
            pass



    except KeyError:
        print('keyerror')
        pass

    

    if key in current_pressed:
        current_pressed.remove(key)


# 开始监听键盘
with keyboard.Listener(on_press=on_press, on_release=on_release) as listener:
    print("正在监听键盘... 按下 j 将触发预设动作。")
    listener.join()